package ch.zhaw.cctd.gui;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.awt.event.*;
import javax.swing.*;
import javax.sound.sampled.*;

/**
 * Kümmert sich um das Laden und die Wiedergabe von Musikdateien
 * 
 * @author Lukas Spirig
 *
 */
public class SoundPlayer {

	private Clip clip;
	private Timer timer;
	private boolean running;

	public SoundPlayer(String path) throws MalformedURLException {
		this(new URL(path));
	}

	public SoundPlayer(URL u) {
		try {
			AudioInputStream ain = AudioSystem.getAudioInputStream(u);
			try {
				DataLine.Info info = new DataLine.Info(Clip.class, ain.getFormat());
				try {
					clip = (Clip) AudioSystem.getLine(info);
					clip.open(ain);
				} catch (LineUnavailableException e) {

				}
				info = null;
			} finally {
				ain.close();
				ain = null;
			}
		} catch (UnsupportedAudioFileException e) {

		} catch (IOException ex) {

		}

		timer = new javax.swing.Timer(100, new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				tick();
			}
		});
	}

	// Abspielen der .wav Datei
	public void play() {
		clip.start();
		timer.start();
		running = true;
	}

	// Zur�cksetzen der .wav Datei
	public void stop() {
		timer.stop();
		clip.stop();
		clip.setMicrosecondPosition(0);
		running = false;
	}

	public void tick() {
		if (!clip.isActive())
			stop();
	}

	public boolean isActive() {
		return running;
	}

	public void finalize() {
		timer = null;
		clip.close();
		clip = null;
	}
}
